/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * 二叉树后序遍历，左右中，递归
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function (root) {
    if (root === null) return []

    let arr = [];

    getTreeNodeVal(root, arr);

    return arr
};

function getTreeNodeVal(root, arr) {
    if (root === null) return
    getTreeNodeVal(root.left, arr)
    getTreeNodeVal(root.right, arr)
    arr.push(root.val)
}


/**
 * 初次迭代遍历
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function(root) {
    if (root === null) return []

    let temp = root,
        stack = [],
        res = [];

    while (stack.length > 0 || temp !== null) {
        while (temp) {
            stack.push(temp)
            temp = temp.left
        }
        if (stack[stack.length - 1].right) {
            temp = stack[stack.length - 1].right
            continue
        }
        if (stack.length > 1 && stack[stack.length - 1] === stack[stack.length - 2].right) {
            while (stack.length > 1 && stack[stack.length - 1] === stack[stack.length - 2].right) {
                res.push(stack.pop().val)
            }
            res.push(stack.pop().val)
            if (stack.length > 0) {
                temp = stack[stack.length - 1].right
            }
            continue
        }
        res.push(stack.pop().val)
        temp = stack.length > 0 ? stack[stack.length - 1].right : null
    }

    return res
};

/**
 * 优化后的后序遍历迭代
 * @param {TreeNode} root
 * @return {number[]}
 */
var postorderTraversal = function (root) {
    if (root === null) return []

    let res = [],
        stack = [],
        temp = root,
        prevPop = null,
        lastNode = null;

    while (temp !== null || stack.length > 0) {
        // 左边判断完成
        while (temp !== null) {
            stack.push(temp)
            temp = temp.left
        }

        lastNode = stack[stack.length - 1]
        if(lastNode.right !== null && lastNode.right !== prevPop){
            // 右边判断完成
            temp = lastNode.right
        }else{
            // 中间判断完成
            res.push(lastNode.val)
            prevPop = stack.pop()
            temp = null
        }
    }

    return res
};

function TreeNode(val, left, right) {
    this.val = (val === undefined ? 0 : val)
    this.left = (left === undefined ? null : left)
    this.right = (right === undefined ? null : right)
}

let a = new TreeNode(1)
a.right = new TreeNode(2)
a.right.left = new TreeNode(3)

console.log(postorderTraversal(a));